package com.github.cyf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.cyf.util.MinioUtil;
import com.github.cyf.domain.entity.UploadResult;
import com.github.cyf.domain.po.SysOss;
import com.github.cyf.exception.ServiceException;
import com.github.cyf.mapper.SysOssMapper;
import com.github.cyf.service.SysOssService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;

/**
 * @author chenyifan
 * @create 2024-03-16 14:33
 */
@Service
@RequiredArgsConstructor
public class SysOssServiceImpl extends ServiceImpl<SysOssMapper, SysOss> implements SysOssService {

    private final MinioUtil minioUtil;

    @Override
    public SysOss upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        UploadResult uploadResult;
        try {
            uploadResult = minioUtil.uploadBySuffix(file.getBytes(), extension, file.getContentType());
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
        // 保存文件信息
        return buildResultEntity(originalFilename, extension, uploadResult);
    }

    public SysOss buildResultEntity(String originalFilename, String extension, UploadResult uploadResult) {
        SysOss sysOss = new SysOss();
        sysOss.setOriginalName(originalFilename);
        sysOss.setFileSuffix(extension);
        sysOss.setFileName(uploadResult.getFilename());
        sysOss.setUrl(uploadResult.getUrl());
        sysOss.setCreateTime(LocalDateTime.now());
        this.save(sysOss);
        return sysOss;
    }

}
